import { overallOptions } from '@/api/public'
import cache from '@/plugins/cache'
import {difference, assign, uniq, reject} from 'lodash'


const enumCacheName = 'publish_enums'

let timer
let nameGroup = []
let taskFn = []

/**
 * 获取字典
 * @param name 字典下拉
 * @param callBack 任务回调
 */
const getEnum = (name, callBack) => {
    return new Promise( async (resolve, reject) => {
        try {
            if (Array.isArray(name)) {
                nameGroup = [...nameGroup, ...name]
            } else {
                nameGroup.push(name)
            }
            // 将任务挂起。
            if (callBack) taskFn.push(callBack)
            timer && clearTimeout(timer)
            timer = setTimeout(async () => {
                if (!nameGroup.length) resolve({})
                nameGroup = uniq(nameGroup)
                let resEnum = cache.session.getJSON(enumCacheName) || {}
                for (const item of nameGroup) {
                    const cacheEnums = getEnumForCache(item)
                    if (cacheEnums && cacheEnums.length) resEnum[item] = cacheEnums
                }
                const differenceKeys = difference(nameGroup, Object.keys(resEnum))
                if (differenceKeys.length > 0) {
                    const res = await overallOptions({
                        option: 'new',
                        params: differenceKeys
                    })
                    if (res.status === 200) {
                        const originEnums = res.data
                        resEnum = assign(resEnum, originEnums)
                        const tryDiff = difference(nameGroup, Object.keys(resEnum))
                        tryDiff.forEach(v => {
                            resEnum[v] = []
                        })
                    }
                }
                taskFn.forEach(item => item(resEnum))
                cache.session.setJSON(enumCacheName, resEnum)
                timer = null
                nameGroup.length = 0
                taskFn.length = 0
                resolve(resEnum)
            }, 200)
        } catch (e) {
            reject(e)
        }
    })
}

const getEnumForCache = name => {
    const enums = cache.session.getJSON(enumCacheName)
    if (enums) return enums[name]
    return null
}

export {
    getEnum
}